// pages/my/order/orderDetails/orderDetails.js
import Config from "../../common/config.js";
var sessionId = wx.getStorageSync('sessionId');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderList: {},
    userinfo: {},
    money: "",
    ordernum: "",
    open: false,
    num: "",
    youhuiArr: [],
    dikou: "",
    payOrderId: "",
    couponId: "",
    netprice: "",
    id: "",
    bookId: "",
    pageSize: "",
    amount: "",
    timeStamp: "",
    nonceStr: "",
    paySign: "",
    package: "",
    status: "",
    biaoshi: "",
    curIdx: null,
    selSta: "1",
    payid: "",
    buy: "",
    ischoose: "false",
    num: 1,
    yy: "",
    idd:"",
    sd:"",
    level: ''
  },
  chooseImg: function (e) {
    console.log(e.currentTarget.dataset.current)
    this.setData({
      curIdx: e.currentTarget.dataset.current
    })
  },
  choose: function () {
    console.log("9999")
    if (this.data.curIdx == 0) {
      this.setData({
        curIdx: null
      })
    }
  },
  selAdree: function (e) {
    console.log(e.currentTarget.dataset.pay)
    this.setData({
      payid: e.currentTarget.dataset.pay
    })
    var that = this
    if (that.data.selSta == 1) {
      that.setData({
        selSta: 2
      })
    } else if (that.data.selSta == 2) {
      that.setData({
        selSta: 1
      })
    }
  },

  showitem: function () {
    this.setData({
      open: !this.data.open
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  selAddree: function (e) {
    var sessionId = wx.getStorageSync('sessionId')
    var that = this
    var valindex = e.currentTarget.dataset.index
    var valId = e.currentTarget.id
    console.log(valId)
    this.setData({
      indexAdree: valindex,
    })
  },

  onLoad: function (options) {
    console.log("qqqqqqqqqqqq",options);
    this.setData({
      buy: options.buy,
      bookId: options.bookId||'',
      amount: options.number,
      id: options.id
    })
    if(!this.data.bookId){
      console.log("bookid是undefined")
      this.setData({
        bookId:""
      })
    }
    console.log(this.data.amount)
    if (options.orderNum) {
      this.setData({
        biaoshi: options.orderNum
      })
    }
    this.setData({
      status: options.status
    })
    var that = this


    wx.setStorage({
      key: 'orderId',
      data: that.data.id,
    })
    if(options.number) {
      wx.setStorage({
        key: 'number',
        data: options.number,
      })
    }
    if(options.bookId){
      wx.setStorage({
        key: 'bookId',
        data: options.bookId
      })
    }
    console.log("这是bookId", this.data.bookId);
    // var sessionId = wx.getStorageSync('sessionId')
    if (options.number){
      wx.request({
        url: Config.url + '/api/pay/downOrder',
        // url: Config.url + '/api/pay/order',
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'accessToken': wx.getStorageSync('sessionId')
        },
        data: {
          // id: options.id || '', //订单id，书id，书的页数
          bookId: options.bookId || '',
          amount: options.number || '',
          // amount: 1,
          // consigneeId: options.addid || ''
          consigneeId: '',
          id: ''
        },
        success(res) {

          console.log(res.data.data.order);
          that.setData({
            orderList: res.data.data.order,
            userinfo: res.data.data.order.consigneeInfo,
            money: res.data.data.order.netPrice,
            payOrderId: res.data.data.order.payOrderId,
            yy: res.data.data.order.originalPrice,
            level: res.data.data.order.level
          })

          wx.setStorage({
            key: 'idd',
            data: res.data.data.order.id,
          })
          wx.setStorage({
            key: 'sta',
            data: res.data.data.order.status,
          })

          console.log(that.data.orderList);
        }
      })
    }else{
      // debugger
      wx.getStorage({
        key: 'idd',
        success: function(res) {
          console.log("111111111111",res.data);
          that.setData({
            sd: res.data
          })
          wx.request({
            url: Config.url + '/api/pay/downOrder',
            // url: Config.url + '/api/pay/order',
            method: 'POST',
            header: {
              'content-type': 'application/json',
              'accessToken': wx.getStorageSync('sessionId')
            },
            data: {
              id: that.data.sd, //订单id，书id，书的页数
              // id:304,
              bookId: '',
              amount: options.number || '',
              consigneeId: options.addid || ''
            },
            success(res) {
              console.log(res.data.data.order);
              that.setData({
                orderList: res.data.data.order,
                userinfo: res.data.data.order.consigneeInfo,
                money: res.data.data.order.netPrice,
                payOrderId: res.data.data.order.orderId,
                yy: res.data.data.order.originalPrice
              })

              console.log(that.data.orderList);
            }
          })
        },
      })
      // wx.request({
      //   url: Config.url + '/api/pay/downOrder',
      //   // url: Config.url + '/api/pay/order',
      //   method: 'POST',
      //   header: {
      //     'content-type': 'application/json',
      //     'accessToken': wx.getStorageSync('sessionId')
      //   },
      //   data: {
      //     id: that.data.sd, //订单id，书id，书的页数
      //     // id:304,
      //     bookId:'',
      //     amount: options.number || '',
      //     consigneeId: options.addid || ''
      //   },
      //   success(res) {

      //     console.log(res.data.data.order);
      //     that.setData({
      //       orderList: res.data.data.order,
      //       userinfo: res.data.data.order.consigneeInfo,
      //       money: res.data.data.order.netPrice,
      //       payOrderId: res.data.data.order.orderId,
      //       yy: res.data.data.order.originalPrice
      //     })

      //     console.log(that.data.orderList);
      //   }
      // })
    }
 
      //设置id缓存传递到地址列表
      wx.setStorage({
        key: 'id',
        data: that.data.id
      })
    // 可用优惠券数量
    wx.request({
      url: Config.url + '/api/userCoupon/get_coupon_able_count',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      success: function (res) {
        console.log(res.data.data);
        that.setData({
          num: res.data.data.userCouponCount
        })
      }
    })
    //调取可用优惠券接口
    wx.request({
      url: Config.url + '/api/userCoupon/getUserCouponList',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        status: "1"
      }, //1可用

      success: function (res) {
        console.log(res.data.data.data);
        that.setData({
          youhuiArr: res.data.data.data
        })
      }
    })

  },
  downorder: function () {
    var that = this;
    console.log(that.data.bookId);
    wx.request({
      url: Config.url + '/api/pay/downOrder',
      // url: Config.url + '/api/pay/order',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        id: '', //订单id，书id，书的页数
        bookId: wx.getStorageSync('bookId') || '',
        amount: wx.getStorageSync('number') || '',
        consigneeId: '',
        type: "1"
      },
      success(res) {
        console.log(res.data.data.order.payOrderId)
        that.setData({
          payOrderId: res.data.data.order.payOrderId
        })
      }
    })
  },

  msg: function (e) {
    var obj = this;
    console.log(e.currentTarget.dataset.num);
    // let youhuiquanid = e._relatedInfo.anchorTargetText;
    // youhuiquanid = youhuiquanid.substring(" ", 1);
    // console.log(youhuiquanid)
    this.setData({
      open: !this.data.open,
      dikou: e._relatedInfo.anchorTargetText,
      couponId: e.currentTarget.dataset.num,
      ischoose: "true"
    });

    // 调取实际付款接口
    wx.request({
      url: Config.url + '/api/pay/get_net_price',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        payOrderId: obj.data.payOrderId || '', //订单号
        couponId: obj.data.couponId, //优惠券编号
        money: obj.data.yy //原价
      },
      success: function (res) {
        console.log(res.data.data.netMoney);
        obj.setData({
          money: res.data.data.netMoney
        })
      }

    })
  },
  // 支付 1余额支付，2微信支付
  gopaymoney: function () {
    var obj = this;

    if (obj.data.payid == 1) {
      wx.request({
        url: Config.url + '/api/pay/pre_pay_by_wallet',
        method: "POST",
        header: {
          'content-type': 'application/json',
          'accessToken': wx.getStorageSync('sessionId')
        },
        data: {
          netMoney: obj.data.money,
          payOrderId: obj.data.payOrderId,
        },
        success: function (res) {
          if (res.data.code == 205) {
            wx.showModal({
              title: '提示',
              content: '您的钱包余额不足',
            })
            return
          };
          if (res.data.code == 300){
            wx.showModal({
              title: '提示',
              content: '请输入收货地址',
            })
            return
          }
          console.log(res);
          wx.navigateTo({
            url: '../payresult/payresult',
          })
        }
      })
    } else {
      wx.request({
        url: Config.url + '/api/pay/pre_pay_order',
        method: "POST",
        header: {
          'content-type': 'application/json',
          'accessToken': wx.getStorageSync('sessionId')
        },
        data: {
          netMoney: obj.data.money,
          payOrderId: obj.data.payOrderId
        },
        success: function (res) {
          if (res.data.code == 300) {
            wx.showModal({
              title: '提示',
              content: '请输入收货地址',
            })
            return
          }
          wx.requestPayment({
            // 'timeStamp': res.data.data.mapResult.timeStamp,
            // 'nonceStr': res.data.data.mapResult.nonceStr,
            // 'package': res.data.data.mapResult.package,
            // 'signType': 'MD5',
            // 'paySign': res.data.data.mapResult.paySign,
            'timeStamp': res.data.data.mapResult.timeStamp,
            'nonceStr': res.data.data.mapResult.nonceStr,
            'package': res.data.data.mapResult.package,
            'signType': res.data.data.mapResult.signType,
            'paySign': res.data.data.mapResult.paySign,
            'success': function (res) {
              console.log(res);
              //跳转到支付结果
              wx.navigateTo({
                url: '../payresult/payresult',
              })
            },
            'fail': function () {
              // let that = this;
              wx.getStorage({
                key: 'sta',
                success: function(res) {
                  if(res.data!=1){
                    wx.getStorage({
                      key: 'idd',
                      success: function (res) {
                        obj.setData({
                          idd: res.data
                        })
                        wx.request({
                          url: Config.url + '/api/pay/edit_status',
                          method: "POST",
                          header: {
                            'content-type': 'application/json',
                            'accessToken': wx.getStorageSync('sessionId')
                          },
                          data: { status: 1 },
                          success: function (res) {

                          }
                        })
                        console.log(obj.data.idd);
                      },
                    });
                  }
                },
              })
           
           
              wx.showModal({
                title: '提示',
                content: '支付失败',
              })
              
            },
          });

        }
      })
    }

  },
  // 跳转到优惠券
  toyouhuiquan: function () {
    wx.navigateTo({
      url: '../choose_coupon/choose_coupon',
    })
  },
  // 跳转到收货列表
  toaddress: function (e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../adressList/adressList?dingdanid=' + e.currentTarget.dataset.id + "&zf=" + 9 + '&bookId=' + this.data.bookId + '&amount=' + this.data.amount ,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // if (this.data.curIdx==0){
    //   this.setData({
    //     curIdx:null
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})